import datetime

import xmltodict

# Create your views here.

import time
from mws import mws
from rest_framework.response import Response
from orders.models import Orders
from orders.serializers import UpdateTimeSerializer
from orders.views import data_to_mysql2, data_to_mysql1
from store.models import StoreManagement
from users.models import User
from vne_erp.utils.iosformat import isoformat
from apscheduler.schedulers.background import BackgroundScheduler
from django_apscheduler.jobstores import DjangoJobStore, register_events, register_job

import time

from tomorrow import threads


access_key = 'AKIAJGOQGGTWX4ICHVZQ'  # replace with your access key

marketplaceids = ['A1AM78C64UM0Y8', 'A2EUQ1WTGCTBG2', 'ATVPDKIKX0DER']

secret_key = 'SjLuwkvF46VCiPzmlFwP8+aPYjA7BNP3IazSyD0l'  # replace with your secret key


class MysqlOfOrderUpdate:

    def get_store_list(self):
        store_info = StoreManagement.objects.all()
        return store_info

    @threads(3)
    def let_mysql_order_update(self, i):

        """
        既然是更新订单就得以 上次更新时间为开始时间   现在时间为结束时间 开始更新   所以得有一个字段记录更新时间
        CreatedAfter = 数据库查询上次的更新时间
        CreateBefore = datetime.datetime.now()

        # """
        print(f"{i.store}开始更新")
        data_str_list = list()


        # 2 遍历每一组 SellerId MWSAuthToken  发起请求 获取响应数据


        if len(Orders.objects.filter(SellerStore=i.id)) == 0:
            order_update_time = datetime.datetime(2019, 8, 1)
        else:
            order_update_time = i.order_update_time

        CreatedAfter = isoformat(order_update_time)

        data_dict = dict()
        SellerId = i.seller_id if i.seller_id != '' else ''
        MWSToken = i.mws_token if i.mws_token != '' else ''
        staff_id = i.staff_id
        store_id = i.id
        store_name = i.store
        staff_name = User.objects.filter(id=staff_id)[0].username
        time.sleep(1)


        x = mws.Orders(access_key=access_key, secret_key=secret_key, account_id=str(SellerId), auth_token=str(MWSToken))
        try:
            orders = x.list_orders(created_after=CreatedAfter, marketplaceids=marketplaceids)
        except Exception as e:
            return Response({"error_msg": str(e)})

        response_data = orders.original
        xml_dict = xmltodict.parse(response_data)
        staff_info = {'staff_id': staff_id, 'staff_name': staff_name}
        store_info = {'store_name': store_name}
        xml_dict['store_info'] = store_info
        xml_dict['staff_info'] = staff_info
        xml_dict = xml_dict["ListOrdersResponse"]["ListOrdersResult"]['Orders']

        if xml_dict is not None:
            # time.sleep(5)

            for j, k in xml_dict.items():

                if not isinstance(k, list):
                    if k["OrderStatus"] == "Canceled":
                        k['SellerStore'] = i.id
                        data_to_mysql2(k, store_id)
                    elif k['OrderStatus'] == 'Unshipped':
                        data_to_mysql1(k, store_id)
                    elif k['OrderStatus'] == 'Shipped':
                        data_to_mysql2(k, store_id)
                    else:
                        pass
                else:
                    for o in k:


                        o['SellerStore'] = i.id
                        if o['OrderStatus'] == 'Shipped':
                            data_to_mysql1(o, store_id)
                        elif o['OrderStatus'] == 'Unshipped':

                            data_to_mysql1(o, store_id)
                        elif o['OrderStatus'] == 'Canceled':
                            data_to_mysql2(o, store_id)
                        else:
                            pass
            if not isinstance(xml_dict["Order"], list):
                data_str = store_name + "同步成功，更新1条订单"
            else:
                data_str = store_name + "同步成功，更新" + str(len(xml_dict["Order"])) + "条订单"
            data_str_list.append(data_str)


        else:
            data_str = store_name + "同步成功，更新0条订单"
            data_str_list.append(data_str)


        now_time = (datetime.datetime.now() - datetime.timedelta(minutes=2)).strftime("%Y-%m-%d %H:%M")
        order_update_time = {"order_update_time": now_time}
        serializer = UpdateTimeSerializer(data=order_update_time)
        serializer.is_valid()
        i.order_update_time = serializer.data['order_update_time']
        i.save()

        update_status = "更新完毕"
        print(update_status)

#开启定时工作
try:
    # 实例化调度器
    scheduler = BackgroundScheduler()
    # 调度器使用DjangoJobStore()
    scheduler.add_jobstore(DjangoJobStore(), "default")
    # 设置定时任务，选择方式为interval，时间间隔为10s
    # 另一种方式为每天固定时间执行任务，对应代码为：
    # @register_job(scheduler, 'cron', day_of_week='mon-fri', hour='9', minute='30', second='10',id='task_time')
    @register_job(scheduler,"interval", minutes=10)
    def my_job():
        # 这里写你要执行的任务
        task = MysqlOfOrderUpdate()
        store_list = task.get_store_list()
        max_num = len(store_list)
        for i in range(max_num):
            task.let_mysql_order_update(store_list[i])
    register_events(scheduler)
    scheduler.start()
except Exception as e:
    print(e)
    # 有错误就停止定时器
    scheduler.shutdown()